package cn.mrcode.smartPluginSecurity;

import cn.mrcode.smartPluginSecurity.realm.SmartCustomRealm;
import cn.mrcode.smartPluginSecurity.realm.SmartJdbcRealm;
import org.apache.shiro.cache.MemoryConstrainedCacheManager;
import org.apache.shiro.mgt.CachingSecurityManager;
import org.apache.shiro.mgt.RealmSecurityManager;
import org.apache.shiro.realm.Realm;
import org.apache.shiro.web.mgt.WebSecurityManager;
import org.apache.shiro.web.servlet.ShiroFilter;

import java.util.LinkedHashSet;
import java.util.Set;

/**
 * @author zhuqiang
 * @version V1.0
 * @date 2015/11/16 20:12
 */
public class SmartSecurityFilter extends ShiroFilter {
    @Override
    public void init() throws Exception {
        super.init();
        WebSecurityManager webSecurityManager = super.getSecurityManager();
        setRealms(webSecurityManager); //
        setCache(webSecurityManager); //设置缓存，降低数据库查询次数，降低i/o访问
    }

    /**
     * 设置realm，可同时支持多个realm。并按照先后顺序用逗号分割
     * 读取到客户端配置文件的realm项，然后判断调用我们实现好的 realm。
     * @param webSecurityManager
     */
    private void setRealms(WebSecurityManager webSecurityManager) {
        String securityRealms = SecurityConfig.getRealms(); //读取配置项
        if(securityRealms != null){
            String[] securityRealmsArray = securityRealms.split(",");
            Set<Realm> realms = new LinkedHashSet<Realm>();
            for (String securityRealm : securityRealmsArray) {
                if(securityRealm.equalsIgnoreCase(SecurityConstant.REALMS_JDBC)){
                    addJdbcRealm(realms);
                }else if (securityRealm.equalsIgnoreCase(SecurityConstant.REALMS_CUSTOM)){
                    addCustomRealm(realms);
                }
            }
            RealmSecurityManager manager = (RealmSecurityManager) webSecurityManager;
            manager.setRealms(realms);
        }
    }

    /**
     * 添加自己实现的 customRealm
     * @param realms
     */
    private void addCustomRealm(Set<Realm> realms) {
       SmartSecurity smartSecurity = SecurityConfig.getSmartSecurity();
       SmartCustomRealm smartCustomRealm = new SmartCustomRealm(smartSecurity);
       realms.add(smartCustomRealm);
    }

    /** 添加自己实现的 jdbcRealm **/
    private void addJdbcRealm(Set<Realm> realms) {
        SmartJdbcRealm smartJdbcRealm = new SmartJdbcRealm();
        realms.add(smartJdbcRealm);
    }

    /** 添加缓存 */
    private void setCache(WebSecurityManager webSecurityManager) {
        if(SecurityConfig.isCache()){
            CachingSecurityManager cachingSecurityManager = (CachingSecurityManager) webSecurityManager;
            cachingSecurityManager.setCacheManager(new MemoryConstrainedCacheManager()); //设置基于内存的缓存
        }
    }
}
